<template>
  <el-dialog
    v-model="state.dialogVisible"
    :append-to-body="true"
    :before-close="close"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    :destroy-on-close="true"
    top="5vh"
    :modal="model"
    :title="state.dialogTitle"
    :width="width"
  >
    <el-form
      ref="formRef"
      label-width="100px"
      :model="state.formData"
      :rules="state.formRules"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="上级节点:" prop="pid">
            <el-input v-model="state.formData.pname" :readonly="true">
              <template #append>
                <el-button icon="Search" @click="openParentNodeSelector" />
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="节点名称:" prop="nodeName">
            <el-input
              v-model="state.formData.nodeName"
              :maxlength="32"
              :show-word-limit="true"
              type="text"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="节点编号:" prop="nodeCode">
            <el-input
              v-model="state.formData.nodeCode"
              :maxlength="32"
              :show-word-limit="true"
              type="text"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="节点状态:" prop="status">
            <easy-dict-select
              ref="systemtreeRef"
              :default-value="state.formData.status"
              dict-code="1022"
              show-all="N"
              expanding
              @change="handleNodeStatusChange"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="排序号:" prop="orderNo">
            <el-input v-model="state.formData.orderNo" type="number" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注:" prop="remark">
            <el-input
              v-model="state.formData.remark"
              :maxlength="256"
              :rows="4"
              :show-word-limit="true"
              type="textarea"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button icon="circle-close" type="warning" @click="close">
        取消
      </el-button>
      <el-button icon="circle-check" type="primary" @click="save">
        确定
      </el-button>
    </template>
    <TreeNodePicker ref="parentNodeRef" @change="handleParentNodeSelect" />
  </el-dialog>
</template>

<script setup name="SystemTreeNodeEdit">
import { useMessage } from "@/hooks/message";
import {
  addSystemTreeNode,
  updateSystemTreeNode
} from "@/api/admin/system/systemtree/";
import EasyDictSelect from "@/components/dictSelect.vue";
import TreeNodePicker from "@/components/treeNodePicker.vue";
import { cloneObject } from "@/utils/common";

const props = defineProps({
  title: {
    type: String,
    default: "节点"
  },
  width: {
    type: String,
    default: "40%"
  },
  model: {
    type: Boolean,
    default: true
  }
});
const emits = defineEmits(["confirm"]);

const formRef = ref(null);
const parentNodeRef = ref(null);

const state = reactive({
  dialogTitle: props.title,
  dialogVisible: false,
  operationAdd: false,
  formData: {
    id: "",
    nodeCode: "",
    nodeName: "",
    treeId: "",
    status: "0",
    nodeLevel: 1,
    pid: "0",
    pname: "无",
    nodePath: "",
    orderNo: "",
    remark: ""
  },
  formRules: {
    nodeCode: [
      { required: true, message: "节点编号不能为空", trigger: "blur" }
    ],
    nodeName: [
      { required: true, message: "节点名称不能为空", trigger: "blur" }
    ],
    treeId: [{ required: true, message: "所属配置不能为空", trigger: "blur" }]
  }
});

const show = row => {
  if (row && row.id) {
    state.operationAdd = false;
    state.dialogTitle = `修改${props.title}`;
    cloneObject(state.formData, row);
    if (row.pid) {
      state.formData.pid = row.pid;
      if (row.pid != "0" && row.pNodePath.length) {
        state.formData.nodePath = `${row.pNodePath}${row.id}/`;
        state.formData.nodeLevel =
          row.pNodePath.length - row.pNodePath.replaceAll("/", "").length + 1;
      } else {
        state.formData.nodePath = `${row.id}/`;
        state.formData.nodeLevel = 1;
        state.formData.pname = "无";
      }
    }
  } else {
    state.operationAdd = true;
    state.formData.treeId = row.treeId;
    state.formData.status = "0";
    state.dialogTitle = `新增${props.title}`;
  }
  state.dialogVisible = true;
};

const close = () => {
  formRef.value.resetFields();
  state.operationAdd = false;
  state.dialogTitle = props.title;
  state.formData = {
    id: "",
    nodeCode: "",
    nodeName: "",
    treeId: "",
    status: "0",
    pid: "0",
    nodeLevel: 1,
    pname: "无",
    nodePath: "",
    orderNo: "",
    remark: ""
  };
  state.dialogVisible = false;
};

const save = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      let data;
      if (state.operationAdd) {
        addSystemTreeNode(state.formData).then(res => {
          if (res.code === 200) {
            useMessage().success(res.msg);
            emits("confirm", state.formData.pid);
            close();
          } else {
            useMessage().error(res.msg);
          }
        });
      } else {
        updateSystemTreeNode(state.formData).then(res => {
          if (res.code === 200) {
            useMessage().success(res.msg);
            emits("confirm", state.formData.pid);
            close();
          } else {
            useMessage().error(res.msg);
          }
        });
      }
    }
  });
};

const openParentNodeSelector = () => {
  const row = {};
  row.treeId = state.formData.treeId;
  row.pid = "0";
  parentNodeRef.value.show(row);
};

const handleParentNodeSelect = nodes => {
  state.formData.pid = nodes.id;
  state.formData.pname = nodes.text;
  if (nodes.nodeLevel) {
    state.formData.nodeLevel = parseInt(nodes.nodeLevel) + 1;
  } else {
    state.formData.nodeLevel = 2;
  }
  //获取父节点编号
  const nodePreCode = nodes.nodeCode;
  //获取兄弟节点数量
  let nodeCodeNumber = 1;
  if (nodes.subcount) {
    const nodeBrotherCount = nodes.subcount;
    //const nodeBrotherCount = nodeBrother.replace(/\b(0+)/gi, '')
    nodeCodeNumber = parseInt(nodeBrotherCount) + 1;
  }
  //新增节点编号 = 父节点编号 + 兄弟节点数量加1后左侧补0
  const nodeCode = nodeCodeNumber.toString().padStart(2, "0");
  state.formData.nodeCode = nodePreCode + nodeCode;
  state.formData.orderNo = nodeCodeNumber * 10;
};

const handleNodeStatusChange = val => {
  state.formData.status = val;
};

defineExpose({
  show,
  close,
  save
});
</script>

<style lang="scss" scoped>
.el-input__inner {
  width: 140px;
}
</style>
